<?php
namespace Admin\Controller;
use Think\Controller;
class CategoryController extends AdminController {
    public function index(){
        $Category = M('Category');//实例化Gategory对象
        $data = $Category->order('sort asc,u_time desc,id desc')
            ->select();
        $data = get_category($data,GOODS_PID);
        $this->assign('title','商品分类列表');//标题
        $this->assign('data',$data);// 赋值数据集
        $this->display();
    }

    public function add(){
        if(IS_POST){
            $data = I('post.');
            $Category = D('Category');
            $Category->setData($data);
            $res = $Category->insertDb();
            if($res){
                $this->success('添加成功',U('index'));
            }else{
                $this->error('添加失败：'.$Category->getError());
            }
        }else{
            $Category = M('Category');
            $data = $Category->order('sort asc,u_time desc,id desc')
                ->select();
            $data = get_category($data,GOODS_PID);
            $this->assign('home_pid',GOODS_PID);
            $this->assign('column_arr',$data);// 赋值数据集
            $this->assign('title','商品分类添加');//标题
            $this->display();
        }
    }


    public function edit($id = 0){
        if($id < 1){
            $this->error('参数错误');
        }
        if(IS_POST){
            $data = I('post.');
            $Category = D('Category');
            $Category->setData($data);
            $res = $Category->updateDb();
            if($res){
                $this->success('修改成功',U('index'));
            }else{
                $this->error('修改失败：'.$Category->getError());
            }
        }else{
            $Category = M('Category');
            $one  = M('Category')->find($id);
            $data = $Category->order('sort asc,u_time desc,id desc')
                ->select();
            $data = get_category($data,2,1);
//            dump($data); exit;
            $this->assign('home_pid',GOODS_PID);
            $this->assign('one',$one);
            $this->assign('column_arr',$data);
            $this->assign('title','产品分类修改');//标题
            $this->display();
        }
    }


    public function delete($id){
        if($id<1){
            $this->error('参数错误,至少选择一条数据');
        }
        // var_dump($id);exit;
        if($id < 1){
            $this->error('参数错误,至少选择一条数据');
        }
        $one = M('Category')->field('id')->where('pid = '.$id)->find();
        if($one){
            $this->error('删除失败,请先删除该菜单栏下面的所有子菜单栏',U('index'));
        }
        $res = M('Category')->delete($id);
        if($res !== false){
            $this->success('删除成功',U('index'));
        }else{
            $this->error('删除失败',U('index'));
        }
    }

}


